package top.jianx.demo.shiro.controller;

import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import top.jianx.demo.shiro.pojo.User;
import top.jianx.demo.shiro.service.UserService;

import javax.validation.Valid;

/**
 * @Description
 * @ClassName UserController
 * @Author Jianx  <[email]jianx@jianx.top>
 * @date 2020.03.03
 */
@Controller
public class RoleController {
    @Autowired
    private UserService UserService;

    @ApiOperation(value = "权限认证通过后跳转sse.html")
    @GetMapping("/what")
    public String why(){
        return "sse";
    }

    @ApiOperation(value = "权限认证通过后跳转one.html")
    @GetMapping("/one")
    public String getOne(){
        return "one";
    }

    @ApiOperation(value = "权限认证通过后跳转two.html")
    @GetMapping("/two")
    public String getTwo(){
        return "two";
    }

    @ApiOperation(value = "权限认证失败后跳转login.html")
    @GetMapping("/login")
    public String login(){
        return "login";
    }

    @ApiOperation(value = "权限认证通过后跳转成功页面")
    @GetMapping("/permission")
    public String permission(){
        return "permission";
    }

    @ApiOperation(value = "登录请求，进行权限认证")
    @GetMapping("/toLogin")
    public String toLogin(@Valid User user, BindingResult bindingResult, Model model){
        for (ObjectError objerror: bindingResult.getAllErrors()) {
            return objerror.getDefaultMessage();
        }
        //System.out.println(newUser.getName()+newUser.getPassword());
        //shiro用户认证
        //获取subject
        Subject subject = SecurityUtils.getSubject();
        //封装用户数据
        UsernamePasswordToken userToken = new UsernamePasswordToken(user.getName(),user.getPassword());
        //执行登录方法,用捕捉异常去判断是否登录成功
        try {
            subject.login(userToken);
            return "redirect:/what";
        } catch (UnknownAccountException e) {
            //用户名不存在
            model.addAttribute("msg","用户名不存在");
            return "login";
        }catch (IncorrectCredentialsException e) {
            //密码错误
            model.addAttribute("msg","密码错误");
            return "login";
        }

    }
    @GetMapping("/toLogout")
    public String logout(){
        return "login";
    }


//    @GetMapping("/api")
//    public String getApiPage(){
//        return "swagger-ui";
//    }
}
